﻿using System;
using System.Messaging;
using Eff.Commons;

namespace Eff.Net
{
    /// <summary>
    /// 消息队列管理器
    /// </summary>
    public class MessageQueueBase
    {
        private readonly string _mqName;
        private MessageQueue _mbMq;
        private static readonly TimeSpan _timeSpanc = new TimeSpan(0, 0, 0, 0, 1);

        protected MessageQueueBase(string queueName)
        {
            _mqName = ".\\private$\\" + queueName;
            MqInit();
        }
        /// <summary>
        /// 消息队列初始化
        /// </summary>
        private void MqInit()
        {
            //建立统计消息对列
            if (_mbMq == null)
            {
                if (MessageQueue.Exists(_mqName))
                    _mbMq = new MessageQueue(_mqName);
                else
                {
                    _mbMq = MessageQueue.Create(_mqName);
                    _mbMq.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
                }
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg"></param>
        protected virtual void Send(Message msg)
        {
            try
            {
                //                MqInit();
                //                string[] mqTypes = { "System.String" }; //消息类型
                //                var mes = new Message
                //                {
                //                    Body = msg,
                //                    Formatter = new XmlMessageFormatter(mqTypes)
                //                }; //消息
                _mbMq.Send(msg); //发送消息

            }
            catch (Exception ex)
            {
                LogHelper.Log.Debug(ex);
            }
        }

        /// <summary>
        /// 接受消息
        /// </summary>
        /// <returns></returns>
        protected virtual Message Receive()
        {
            //string[] mqTypes = { "System.String" };	//消息类型
            Message message;                       //消息
            try
            {
                //设置了超时间时间，如果超时，就会返回
                message = _mbMq.Receive(_timeSpanc);
            }
            catch (Exception)
            {
                message = null;
            }
            Message msg = null;
            if (message != null)
            {
                msg = message;
                message.Dispose();
            }
            return msg;
        }
    }
}
